const { query } = require('../../../../lib/db');
const { authenticateToken } = require('../../../../lib/auth');
const { logInternalNoteAction } = require('../../../../lib/logger');

async function handler(req, res) {
  try {
    const ticketId = req.query.id;

    switch (req.method) {
      case 'GET':
        return await getInternalNotes(req, res, ticketId);
      case 'POST':
        return await addInternalNote(req, res, ticketId);
      case 'PUT':
        return await updateInternalNote(req, res, ticketId);
      case 'DELETE':
        return await deleteInternalNote(req, res, ticketId);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('内部备注API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取内部备注列表
async function getInternalNotes(req, res, ticketId) {
  // 检查权限：只有支持人员及以上角色可以查看内部备注
  if (req.user.role === 'user') {
    return res.status(403).json({
      success: false,
      message: '无权限查看内部备注'
    });
  }

  try {
    // 根据用户角色过滤可见的备注
    let visibilityFilter = '';
    if (req.user.role === 'support') {
      visibilityFilter = "AND (tin.visibility IN ('all_internal', 'support_only'))";
    } else if (req.user.role === 'operator') {
      visibilityFilter = "AND tin.visibility IN ('all_internal', 'support_only')";
    }
    // 管理员可以查看所有备注

    const notes = await query(`
      SELECT 
        tin.*,
        u.name as user_name,
        u.department as user_department,
        u.role as user_role
      FROM ticket_internal_notes tin
      LEFT JOIN users u ON tin.user_id = u.id
      WHERE tin.ticket_id = ? ${visibilityFilter}
      ORDER BY tin.is_pinned DESC, tin.created_at DESC
    `, [ticketId]);

    res.status(200).json({
      success: true,
      data: notes
    });
  } catch (error) {
    console.error('获取内部备注失败:', error);
    res.status(500).json({
      success: false,
      message: '获取内部备注失败'
    });
  }
}

// 添加内部备注
async function addInternalNote(req, res, ticketId) {
  // 检查权限：只有支持人员及以上角色可以添加内部备注
  if (req.user.role === 'user') {
    return res.status(403).json({
      success: false,
      message: '无权限添加内部备注'
    });
  }

  const { 
    note_content, 
    note_type = 'general', 
    is_pinned = false, 
    visibility = 'all_internal',
    related_field 
  } = req.body;

  if (!note_content || note_content.trim() === '') {
    return res.status(400).json({
      success: false,
      message: '备注内容不能为空'
    });
  }

  try {
    // 验证备注类型
    const validTypes = ['general', 'technical', 'management', 'urgent'];
    if (!validTypes.includes(note_type)) {
      return res.status(400).json({
        success: false,
        message: '无效的备注类型'
      });
    }

    // 验证可见性设置
    const validVisibilities = ['support_only', 'admin_only', 'all_internal'];
    if (!validVisibilities.includes(visibility)) {
      return res.status(400).json({
        success: false,
        message: '无效的可见性设置'
      });
    }

    // 检查可见性权限
    if (visibility === 'admin_only' && req.user.role !== 'administrator') {
      return res.status(403).json({
        success: false,
        message: '无权限设置仅管理员可见'
      });
    }

    // 添加备注
    const result = await query(
      `INSERT INTO ticket_internal_notes 
       (ticket_id, user_id, note_content, note_type, is_pinned, visibility, related_field) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [ticketId, req.user.id, note_content.trim(), note_type, is_pinned, visibility, related_field]
    );

    // 更新工单的内部备注标记
    await query(
      'UPDATE tickets SET is_internal_note_updated = 1, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [ticketId]
    );

    // 获取新添加的备注详情
    const newNote = await query(`
      SELECT 
        tin.*,
        u.name as user_name,
        u.department as user_department
      FROM ticket_internal_notes tin
      LEFT JOIN users u ON tin.user_id = u.id
      WHERE tin.id = ?
    `, [result.insertId]);

    res.status(201).json({
      success: true,
      message: '内部备注添加成功',
      data: newNote[0]
    });
  } catch (error) {
    console.error('添加内部备注失败:', error);
    res.status(500).json({
      success: false,
      message: '添加内部备注失败'
    });
  }
}

// 更新内部备注
async function updateInternalNote(req, res, ticketId) {
  const { noteId, note_content, note_type, is_pinned, visibility } = req.body;

  if (!noteId) {
    return res.status(400).json({
      success: false,
      message: '备注ID不能为空'
    });
  }

  try {
    // 检查备注是否存在
    const existingNote = await query(
      'SELECT * FROM ticket_internal_notes WHERE id = ? AND ticket_id = ?',
      [noteId, ticketId]
    );

    if (existingNote.length === 0) {
      return res.status(404).json({
        success: false,
        message: '备注不存在'
      });
    }

    const note = existingNote[0];

    // 检查权限：只有备注创建者、操作员和管理员可以修改
    if (note.user_id !== req.user.id && 
        !['operator', 'administrator'].includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '无权限修改此备注'
      });
    }

    // 构建更新数据
    const updateFields = [];
    const updateValues = [];

    if (note_content !== undefined) {
      updateFields.push('note_content = ?');
      updateValues.push(note_content.trim());
    }

    if (note_type !== undefined) {
      updateFields.push('note_type = ?');
      updateValues.push(note_type);
    }

    if (is_pinned !== undefined) {
      updateFields.push('is_pinned = ?');
      updateValues.push(is_pinned);
    }

    if (visibility !== undefined) {
      // 检查可见性权限
      if (visibility === 'admin_only' && req.user.role !== 'administrator') {
        return res.status(403).json({
          success: false,
          message: '无权限设置仅管理员可见'
        });
      }
      updateFields.push('visibility = ?');
      updateValues.push(visibility);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有需要更新的字段'
      });
    }

    updateValues.push(noteId);

    // 更新备注
    await query(
      `UPDATE ticket_internal_notes SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
      updateValues
    );

    // 获取更新后的备注
    const updatedNote = await query(`
      SELECT 
        tin.*,
        u.name as user_name,
        u.department as user_department
      FROM ticket_internal_notes tin
      LEFT JOIN users u ON tin.user_id = u.id
      WHERE tin.id = ?
    `, [noteId]);

    res.status(200).json({
      success: true,
      message: '备注更新成功',
      data: updatedNote[0]
    });
  } catch (error) {
    console.error('更新内部备注失败:', error);
    res.status(500).json({
      success: false,
      message: '更新内部备注失败'
    });
  }
}

// 删除内部备注
async function deleteInternalNote(req, res, ticketId) {
  const { noteId } = req.body;

  if (!noteId) {
    return res.status(400).json({
      success: false,
      message: '备注ID不能为空'
    });
  }

  try {
    // 检查备注是否存在
    const existingNote = await query(
      'SELECT * FROM ticket_internal_notes WHERE id = ? AND ticket_id = ?',
      [noteId, ticketId]
    );

    if (existingNote.length === 0) {
      return res.status(404).json({
        success: false,
        message: '备注不存在'
      });
    }

    const note = existingNote[0];

    // 检查权限：只有备注创建者、操作员和管理员可以删除
    if (note.user_id !== req.user.id && 
        !['operator', 'administrator'].includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '无权限删除此备注'
      });
    }

    // 删除备注
    await query('DELETE FROM ticket_internal_notes WHERE id = ?', [noteId]);

    // 记录操作日志
    await logInternalNoteAction(
      ticketId,
      req.user.id,
      'deleted',
      note.note_content,
      req.headers['x-forwarded-for'] || req.connection.remoteAddress,
      req.headers['user-agent']
    );

    res.status(200).json({
      success: true,
      message: '备注删除成功'
    });
  } catch (error) {
    console.error('删除内部备注失败:', error);
    res.status(500).json({
      success: false,
      message: '删除内部备注失败'
    });
  }
}


export default authenticateToken(handler);